package light.head.controller.oa;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.oa.CommunicationDAO;
import light.head.dao.sys.OrganDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.framework.utils.ExcelUtils;
import light.head.model.Communication;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping(value = Url.C_COMMUNICATION)
public class CommunicationController extends SupporterController {

	private final static String fileName = "通讯录导出.xls";
	private final static String workBook_2003_xls = "xls";			// excel 2003及之前的版本
	private final static String workBook_2007_xlsx = "xlsx";		// excel 2007版本
	
	private CommunicationDAO commDAO;
	private OrganDAO organDAO;
	
	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.COMMUNICATION_INIT);
	}
	
	@RequestMapping(value = Url.QUERY)
	public ModelAndView query(String type, HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
		
		Map<String, String> map = createQueryMapByParmName(request, Parm.NAME, Parm.SEX, Parm.COMPANY, Parm.TYPE);
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		map.put(Parm.OC, oc.toString());
		if (commDAO.findByMap(map, pb) == RESULT.SUCCESS) {
			request.setAttribute(Parm.PAGE_BEAN, pb);
		}
		return new ModelAndView(Url.COMMUNICATION_LIST);
	}
	
	@RequestMapping(value = Url.EDIT)
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		if(null == cu_organCode(request)) {
			PageBean pb = createPageBean(request);
			request.setAttribute(Parm.PAGE_BEAN, pb);
			return new ModelAndView(Url.COMMUNICATION_INIT);
		}
		String code = request.getParameter(Parm.CODE);
		if (isNotNull(code)) {
			Communication comm = commDAO.get(Integer.parseInt(code));
			request.setAttribute(Parm.COMMU, comm);
		}else{
			Communication comm = new Communication();
			request.setAttribute(Parm.COMMU, comm);
		}
		return new ModelAndView(Url.COMMUNICATION_EDIT);
	}

	@Transactional
	@RequestMapping(value = Url.SAVE)
	public void save(Communication comm, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		if (null == comm.getCode()) {
			if(null == comm.getName() && null == comm.getPhone()) {
				print(response, Msg.NOT_FIND);
				return;
			}
			comm.setDeleted(false);
			comm.setCu(cu_code(request));
			comm.setCt(new Date());
			comm.setOc(oc);
			result = commDAO.add(comm);
			
		} else {
			result = commDAO.update(comm);
		}
		
		if (RESULT.SUCCESS == result) {
			print(response, Msg.SUCCESS);
		} else 
			print(response, Msg.ERROR);
	}
	
	@RequestMapping(value = Url.DELETE)
	public void delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		Communication comm = commDAO.get(Integer.parseInt(code));
		comm.setDeleted(true);
		if (commDAO.update(comm) == RESULT.SUCCESS) {
			print(response, Msg.SUCCESS);
		} else 
			print(response, Msg.ERROR);
	}

	// 通讯录导入
	@RequestMapping(Url.EXCEL_IMPORT)
	public void exclImport(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		Integer cuCode = cu_code(request);
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		Date ct = new Date();
		
		MultipartHttpServletRequest multipartRequestd = (MultipartHttpServletRequest) request;
		List<MultipartFile> files = multipartRequestd.getFiles("files");
		
		// 头部格式为： 0.性别 1.姓名 2.电话 3.邮箱 4.公司 5.地址, 6.类型 
		List<Communication> list = new ArrayList<Communication>();
		Communication temp = null;
		
		for (MultipartFile file : files) {
			// 判断文件是那个版本的excel
			String excelV = this.checkExcel2003Or2007(file);

			if (workBook_2003_xls.equals(excelV)) {
				// XSSFWorkbook 解析excel 2003及以前的版本 .xls
				HSSFWorkbook hssfWorkbook = new HSSFWorkbook(file.getInputStream());

				// 循环工作表Sheet
				for (int numSheet = 0; numSheet < hssfWorkbook
						.getNumberOfSheets(); numSheet++) {
					HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
					if (hssfSheet == null) {
						continue;
					}
					// 循环行Row
					for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
						HSSFRow hssfRow = hssfSheet.getRow(rowNum);
						if (hssfRow == null) {
							continue;
						}
						temp = new Communication();
						temp.setCu(cuCode);
						temp.setOc(oc);
						temp.setCt(ct);
						// 循环列Cell
						for (int cellNum = 0; cellNum <= hssfRow.getLastCellNum(); cellNum++) {
							HSSFCell hssfCell = hssfRow.getCell(cellNum);
							if (hssfCell == null) {
								continue;
							}
							// 0.性别 1.姓名 2.电话 3.邮箱 4.公司 5.地址, 6.类型
							if (cellNum == 0) {
								String a = hssfCell.getStringCellValue();
								temp.setSex(a.equals("男") ? true : false);
								continue;
							}

							if (cellNum == 1) {
								temp.setName(hssfCell.toString());
								continue;
							}

							// 对手机号码会转成科学计数法处理
							try {
								if (cellNum == 2) {
									DecimalFormat df = new DecimalFormat("0");
									temp.setPhone(df.format(hssfCell.getNumericCellValue()));
									continue;
								}
							} catch (Exception e) {
								temp.setPhone(hssfCell.toString());
								continue;
							}
							if (cellNum == 3) {
								temp.setEmail(hssfCell.toString());
								continue;
							}

							if (cellNum == 4) {
								temp.setCompany(hssfCell.toString());
								continue;
							}

							if (cellNum == 5) {
								temp.setAddress(hssfCell.toString());
								continue;
							}
							if (cellNum == 6) {
								if ("公司".equals(hssfCell))
									temp.setType(Sys.B_THREE);
								else if ("公共".equals(hssfCell))
									temp.setType(Sys.B_TWO);
								else 
									temp.setType(Sys.B_ONE);
							}
							if (cellNum == 7) {
								temp.setBirthday(hssfCell.getDateCellValue());
								continue;
							}
						}
						if (isNotNull(temp.getName()))
							list.add(temp);
					}
				}
			} else if (workBook_2007_xlsx.equals(excelV)) {
				// XSSFWorkbook 解析excel 2007的版本 .xlsx
				XSSFWorkbook hssfWorkbook = new XSSFWorkbook(file.getInputStream());
				// 循环工作表Sheet
				for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
					XSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
					if (hssfSheet == null) {
						continue;
					}
					// 循环行Row 不取第一行，第一行为头部
					for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
						XSSFRow hssfRow = hssfSheet.getRow(rowNum);
						if (hssfRow == null) {
							continue;
						}
						temp = new Communication();
						temp.setCu(cuCode);
						temp.setOc(oc);
						temp.setCt(ct);
						// 循环列Cell
						for (int cellNum = 0; cellNum <= hssfRow.getLastCellNum(); cellNum++) {
							XSSFCell hssfCell = hssfRow.getCell(cellNum);
							if (hssfCell == null) {
								continue;
							}

							// 0.性别 1.姓名 2.电话 3.邮箱 4.公司 5.地址,6.类型,7.生日
							if (cellNum == 0) {
								temp.setSex(hssfCell.equals("男") ? true : false);
								continue;
							}

							if (cellNum == 1) {
								temp.setName(hssfCell.toString());
								continue;
							}

							// 对手机号码会转成科学计数法处理
							try {
								if (cellNum == 2) {
									DecimalFormat df = new DecimalFormat("0");
									temp.setPhone(df.format(hssfCell.getNumericCellValue()));
									continue;
								}
							} catch (Exception e) {
								temp.setPhone(hssfCell.toString());
								continue;
							}
							if (cellNum == 3) {
								temp.setEmail(hssfCell.toString());
								continue;
							}

							if (cellNum == 4) {
								temp.setCompany(hssfCell.toString());
								continue;
							}

							if (cellNum == 5) {
								temp.setAddress(hssfCell.toString());
								continue;
							}
							if (cellNum == 6) {
								if ("公司".equals(hssfCell))
									temp.setType(Sys.B_THREE);
								else if ("公共".equals(hssfCell))
									temp.setType(Sys.B_TWO);
								else 
									temp.setType(Sys.B_ONE);
							}
							if (cellNum == 7) {
								temp.setBirthday(hssfCell.getDateCellValue());
								continue;
							}

						}
						list.add(temp);
					}
				}
			} else {
				print(response, Msg.J_ERROR_ONE);
				return;
			}
			
		} 
		// 保存
		for (Communication comm : list) {
			if (RESULT.SUCCESS != commDAO.add(comm))
				throw new Exception("保存失败");
		}
		
		print(response, Msg.J_SUCCESS);
		
	}

	// 通讯录导出
	@RequestMapping(Url.EXCEL_EXPORT)
	public void exclExport(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, String> map = createQueryMapByParmName(request, Parm.NAME, Parm.SEX, Parm.COMPANY, Parm.TYPE);
		map.put(Parm.CU, cu_code(request).toString());
		map.put(Parm.OC, cu_organCode(request).toString());
		List<Communication> list = commDAO.findAllByMap(map);
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
		ExcelUtils.writeExcel(list, "通讯录", response.getOutputStream(), null, null);
	}

	/**
	 * 判断excel 是那个版本的
	 *@param in	文件
	 *@return	返回：xls (2003及以前版本), xlsx (2007版本)
	 *@throws Exception
	 *@author yangguanghe [2014-6-29_下午1:00:35]
	 */
	private String checkExcel2003Or2007(MultipartFile file) throws Exception {

		try {
			new HSSFWorkbook(file.getInputStream());
			return workBook_2003_xls;
		} catch (Exception e) {
			try {
				new XSSFWorkbook(file.getInputStream());
				return workBook_2007_xlsx;
			} catch (Exception e1) {
				System.out.println("您的Excel 不能被解析");
				e1.printStackTrace();
			}
		}
		return "";
	}

	@Autowired
	public void setCommDAO(CommunicationDAO commDAO) {
		this.commDAO = commDAO;
	}
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}
	
}
